import 'package:flutter/material.dart';
import 'package:fotile_device_connect/WifiStatusPlugin.dart';
import 'FotileIotPlugin.dart'; // SDK 封装 Dart 文件

void main() {
  runApp(const FotileDeviceConnectApp());
}

class FotileDeviceConnectApp extends StatelessWidget {
  const FotileDeviceConnectApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fotile Device Connect',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: const Color(0xFF1976D2),
          brightness: Brightness.light,
        ),
        useMaterial3: true,
        appBarTheme: const AppBarTheme(
          backgroundColor: Color(0xFF1976D2),
          foregroundColor: Colors.white,
          elevation: 0,
        ),
      ),
      home: const DeviceConnectHomePage(),
    );
  }
}

class DeviceConnectHomePage extends StatefulWidget {
  const DeviceConnectHomePage({super.key});

  @override
  State<DeviceConnectHomePage> createState() => _DeviceConnectHomePageState();
}

class _DeviceConnectHomePageState extends State<DeviceConnectHomePage> {
  String _wifiStatus = "未知";
  String _sdkStatus = "未初始化";

  @override
  void initState() {
    super.initState();
    _checkWifi();
  }

  // ================= WiFi =================
  Future<void> _checkWifi() async {
    try {
      final enabled = await WifiStatusPlugin.isWifiEnabled();
      setState(() {
        _wifiStatus = enabled ? "已开启" : "未开启";
      });
    } catch (e) {
      setState(() {
        _wifiStatus = "检测失败: $e";
      });
    }
  }

  Future<void> _openWifiSettings() async {
    try {
      await WifiStatusPlugin.openWifiSettings();
      _checkWifi();
    } catch (e) {
      setState(() {
        _wifiStatus = "打开WiFi设置失败: $e";
      });
    }
  }

  // ================= 定位 =================
  Future<void> _getLocation() async {
    try {
      final location = await WifiStatusPlugin.getCurrentLocation();
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("定位结果：$location")),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("获取定位失败：$e")),
      );
    }
  }

  // ================= 弹窗输入工具 =================
  Future<String?> _showInputDialog(String label) async {
    final controller = TextEditingController();
    return await showDialog<String>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(label),
          content: TextField(controller: controller, decoration: InputDecoration(labelText: label)),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, null), child: const Text("取消")),
            TextButton(onPressed: () => Navigator.pop(context, controller.text.trim()), child: const Text("确认")),
          ],
        );
      },
    );
  }

  Future<Map<String, String>?> _showDeviceInputDialog() async {
    final ssidController = TextEditingController();
    final passwordController = TextEditingController();
    final productIdController = TextEditingController();
    final productTypeController = TextEditingController();

    return await showDialog<Map<String, String>>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text("输入配网信息"),
          content: SingleChildScrollView(
            child: Column(
              children: [
                TextField(controller: ssidController, decoration: const InputDecoration(labelText: "SSID")),
                TextField(controller: passwordController, decoration: const InputDecoration(labelText: "WiFi密码")),
                TextField(controller: productIdController, decoration: const InputDecoration(labelText: "ProductId")),
                TextField(controller: productTypeController, decoration: const InputDecoration(labelText: "ProductType")),
              ],
            ),
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context, null), child: const Text("取消")),
            TextButton(
              onPressed: () => Navigator.pop(context, {
                "ssid": ssidController.text.trim(),
                "password": passwordController.text.trim(),
                "productId": productIdController.text.trim(),
                "productType": productTypeController.text.trim(),
              }),
              child: const Text("确认"),
            ),
          ],
        );
      },
    );
  }

  // ================= SDK =================
  Future<void> _initSdk() async {
    try {
      // 弹窗输入 UserId
      final userId = await _showInputDialog("请输入 UserId");
      if (userId == null || userId.isEmpty) return;

      // 调用原生方法初始化 SDK，参数都在原生写死
      final result = await FotileIotPlugin.init(userId);

      setState(() {
        _sdkStatus = result ?? "SDK 初始化完成";
      });

      // 配置 SDK 额外参数（如果原生已经写死，这里可以不调用）
      await FotileIotPlugin.setDebugMode(true);
      await FotileIotPlugin.setUpSDKTestEnv(false);
      await FotileIotPlugin.setSubDeviceTime(120);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("SDK 初始化完成: $result")),
      );
    } catch (e) {
      setState(() {
        _sdkStatus = "SDK 初始化失败: $e";
      });
    }
  }


  Future<void> _addDevice() async {
    final data = await _showDeviceInputDialog();
    if (data == null) return;

    try {
      final res = await FotileIotPlugin.addDeviceByWifi(
        data["ssid"]!,
        data["password"]!,
        data["productId"]!,
        data["productType"]!,
      );
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("配网结果：$res")));
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("配网失败：$e")));
    }
  }

  Future<void> _stopAddDevice() async {
    final result = await FotileIotPlugin.stopAddDevice();
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("停止配网：$result")));
  }

  Future<void> _destroySdk() async {
    final result = await FotileIotPlugin.destroy();
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("销毁SDK：$result")));
  }

  // ================= 页面 UI =================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fotile 设备连接'),
        actions: [IconButton(icon: const Icon(Icons.refresh), onPressed: _checkWifi)],
      ),
      body: Center(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('WiFi 状态：$_wifiStatus', style: const TextStyle(fontSize: 18)),
              const SizedBox(height: 10),
              TextButton(onPressed: _openWifiSettings, child: const Text('打开 WiFi 设置')),
              const Divider(),
              Text('SDK 状态：$_sdkStatus', style: const TextStyle(fontSize: 16)),
              const SizedBox(height: 10),
              ElevatedButton(onPressed: _initSdk, child: const Text('初始化 SDK')),
              ElevatedButton(onPressed: _addDevice, child: const Text('添加设备')),
              ElevatedButton(onPressed: _stopAddDevice, child: const Text('停止配网')),
              ElevatedButton(onPressed: _destroySdk, child: const Text('销毁SDK')),
              const Divider(),
              ElevatedButton(onPressed: _getLocation, child: const Text("获取精确定位")),
            ],
          ),
        ),
      ),
    );
  }
}
